package tt.dz.biz.service.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javax.annotation.Resource;
import org.apache.avro.Protocol;
import org.apache.avro.Protocol.Message;
import org.apache.avro.generic.GenericRecord;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import tt.dz.base.authentication.entity.RedisUser;
import tt.dz.base.authentication.util.TokenFactory;
import tt.dz.base.redis.service.RedisService;
import tt.dz.biz.service.user.UserService;
import tt.dz.common.DZStringUtil;
import tt.dz.common.DateUtil;
import tt.dz.common.DzConstants;
import tt.dz.common.DzConstants.userLock;
import tt.dz.common.DzConstants.userType;
import tt.dz.common.DzConstants.userValid;
import tt.dz.common.DzDigester;
import tt.dz.common.DzErrorCode;
import tt.dz.common.DzErrorCode.CommonErrorCode;
import tt.dz.common.DzErrorCode.UserErrorCode;
import tt.dz.common.LogUtil;
import tt.dz.vo.OnlineAccountVO;
import tt.dz.vo.UserBaseVO;
import tt.dz.vo.UserDetailVO;

@Service("rpcUserRegisterService")
public class RPCUserRegisterService
  implements RPCBaseService
{
  @Resource(name="userService")
  private UserService userService;
  @Resource(name="tt.dz.base.redis.service")
  private RedisService redisService;
  
  public Object execute(Protocol.Message message, Object request, Protocol protocol)
    throws Exception
  {
    String name = message.getName();
    Object reqJson = ((GenericRecord)request).get("req");
    String resJson = "";
    if ("regist".equals(name)) {
      resJson = regist(reqJson.toString());
    }
    return resJson;
  }
  
  public String regist(String reqJson)
    throws Exception
  {
    JSONObject resObj = new JSONObject();
    Integer isSuccess = Integer.valueOf(0);
    String userID = "";
    String tocken = "";
    boolean isCheck = true;
    StringBuffer errorMsg = new StringBuffer();
    JSONObject reqObj = JSON.parseObject(reqJson);
    String mobileNo = reqObj.getString("mobileNo");
    String password = reqObj.getString("password");
    String channel = reqObj.getString("channel");
    String longitude = reqObj.getString("longitude");
    String latitude = reqObj.getString("latitude");
    String adddetail = reqObj.getString("adddetail");
    String areaCode = reqObj.getString("areaCode");
    String merchantCode = reqObj.getString("merchantCode");
    if ((channel == null) || ("".equals(channel)))
    {
      isCheck = false;
      errorMsg.append("渠道号不能够为空,");
    }
    else if (channel.length() != 3)
    {
      isCheck = false;
      errorMsg.append("渠道号长度为3位,");
    }
    if ((mobileNo == null) || ("".equals(mobileNo)))
    {
      isCheck = false;
      errorMsg.append("手机号码不能够为空,");
    }
    else if (!DZStringUtil.verifyMobileNo(mobileNo))
    {
      isCheck = false;
      errorMsg.append("手机号码格式不正确！,");
    }
    if ((merchantCode == null) || ("".equals(merchantCode)))
    {
      isCheck = false;
      errorMsg.append("运营商编码不能够为空,");
    }
    if ((longitude != null) && (!"".equals(longitude)) && 
      (!DZStringUtil.verifyItude(longitude)))
    {
      isCheck = false;
      errorMsg.append("经度格式不合法 请设置为3位整数6位小数,");
    }
    if ((latitude != null) && (!"".equals(latitude)) && 
      (!DZStringUtil.verifyItude(latitude)))
    {
      isCheck = false;
      errorMsg.append("纬度格式不合法 请设置为3位整数6位小数,");
    }
    boolean isExistsMerchant = this.userService.checkMerchantExists(merchantCode);
    if (!isExistsMerchant)
    {
      isCheck = false;
      errorMsg.append("运营商：" + merchantCode + "不存在请核实,");
    }
    boolean isExistsUser = this.userService.checkMobileExists(mobileNo, merchantCode);
    if (isExistsUser)
    {
      isCheck = false;
      errorMsg.append("手机号码：" + mobileNo + "已经注册请核实,");
    }
    if (isCheck)
    {
      int result;
      try
      {
        String userSeq = this.userService.queryUserSequence();
        if (userSeq == null) {
          throw new NullPointerException("获取的Seq值为空，请核查。");
        }
        userID = 
          DzConstants.userType.PERSONAL_CUSTOMER.value() + channel + DateUtil.getDateFormatter() + DZStringUtil.getFixedLengthString(8, userSeq);
        String salt = DZStringUtil.getRandomString(6);
        UserBaseVO baseVo = new UserBaseVO();
        baseVo.setUserId(userID);
        baseVo.setMobileNo(mobileNo);
        baseVo.setRegistTime(DateUtil.getDBCurrentTime());
        baseVo.setUserType(DzConstants.userType.PERSONAL_CUSTOMER.value());
        if (!StringUtils.isEmpty(password))
        {
          baseVo.setPassword(DzDigester.md5ForUser(password, salt));
          baseVo.setSalt(salt);
        }
        baseVo.setIsLocked(DzConstants.userLock.UNLOCK.value());
        baseVo.setIsValid(DzConstants.userValid.VALID.value());
        baseVo.setMerchantCode(merchantCode);
        
        UserDetailVO detailVO = new UserDetailVO();
        detailVO.setUserId(userID);
        detailVO.setDistrictCode(areaCode);
        if (StringUtils.isNotBlank(longitude)) {
          detailVO.setLongitude(Double.valueOf(longitude));
        }
        if (StringUtils.isNotBlank(latitude)) {
          detailVO.setLatitude(Double.valueOf(latitude));
        }
        detailVO.setAddDetail(adddetail);
         result = this.userService.saveregister(baseVo, detailVO);
        areaCode = areaCode == null ? "0028" : areaCode;
        OnlineAccountVO onlineAccountVO = this.userService.generateOnlineAccount(areaCode, baseVo.getUserId());
        boolean excuteFlag = this.userService.insertOnlineAccount(onlineAccountVO);
        result = excuteFlag ? 1 : 0;
      }
      catch (Exception e)
      {
        LogUtil.error("保存注册数据发生异常", e);
        errorMsg.append("保存注册数据发生异常");
        result = 0;
      }
      isSuccess = Integer.valueOf(result > 0 ? 1 : 0);
      if (isSuccess.intValue() == 1)
      {
        tocken = TokenFactory.getInstance().sign(mobileNo);
        saveRedis(userID, mobileNo, tocken);
      }
      else
      {
        resObj.put("errorCode", DzErrorCode.CommonErrorCode.SAVE_ERROR.value());
        resObj.put("errorMsg", errorMsg);
      }
    }
    else
    {
      if (errorMsg.length() > 1) {
        errorMsg.deleteCharAt(errorMsg.length() - 1);
      }
      resObj.put("errorCode", DzErrorCode.UserErrorCode.HAS_EXISTED.value());
      resObj.put("errorMsg", errorMsg);
    }
    resObj.put("mobileNo", mobileNo);
    resObj.put("isSuccess", isSuccess);
    resObj.put("userId", userID);
    resObj.put("tocken", tocken);
    String resJson = JSON.toJSONString(resObj);
    return resJson;
  }
  
  private void saveRedis(String userID, String mobileNo, String token)
  {
    try
    {
      long cTime = System.currentTimeMillis();
      RedisUser tmpUser = new RedisUser();
      tmpUser.setIsOnline(1);
      tmpUser.setLastUpdateTime(cTime);
      tmpUser.setCreateTime(cTime);
      tmpUser.setToken(token);
      tmpUser.setIsLocked(0);
      tmpUser.setLoginCount(0);
      tmpUser.setUserId(userID);
      this.redisService.saveUser(mobileNo, tmpUser);
    }
    catch (Exception e)
    {
      LogUtil.error("注册用户保存token失败，参数为：userID=" + userID + ",mobileNo=" + mobileNo + ",token=" + token);
    }
  }
}
